import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:flutter/widgets.dart';
import 'dart:io';
import 'dart:convert';
import 'package:new_obj/model/picmodel.dart';
import 'package:cached_network_image/cached_network_image.dart';

class commendInfo extends StatefulWidget {
  commendInfo({Key key}) : super(key: key);

  @override
  _commendInfoState createState() => _commendInfoState();
}

class _commendInfoState extends State<commendInfo>
    with AutomaticKeepAliveClientMixin {
  List<PicModel> picList = new List();
  int page = 1;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      body: new GridView.builder(
        padding: const EdgeInsets.all(1.0),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2, mainAxisSpacing: 2.0, crossAxisSpacing: 2.0),
        itemCount: picList.length,
        itemBuilder: (BuildContext contenxt, int index) {
          if (index == picList.length - 1) {
            _getPicList();
          }
          return buildItem(picList[index]);
        },
      ),
    );
  }

  //创建布局
  buildItem(item) {
    return new GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            new MaterialPageRoute(
                builder: (context) => new Scaffold(
                      appBar: new AppBar(
                        title: new Text('图片详情'),
                      ),
                      body: new Center(
                          child: new Container(
                        width: 300.0,
                        child: new CachedNetworkImage(
                          imageUrl: item.img,
                          imageBuilder: (context, imageProvider) => Container(
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: imageProvider,
                                  fit: BoxFit.cover,
                                  colorFilter:
                                  ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
                            ),
                          ),
                          placeholder: (context, url) => CircularProgressIndicator(),
                          fadeInDuration: new Duration(seconds: 3),
                          fadeOutDuration: new Duration(seconds: 1),
                          fit: BoxFit.fitWidth,
                        ),
                      )),
                    )));
      },
      child: new CachedNetworkImage(
        errorWidget: (context, url, error) => new Icon(Icons.error),
        imageUrl: item.img,
        imageBuilder: (context, imageProvider) => Container(
          decoration: BoxDecoration(
            image: DecorationImage(
                image: imageProvider,
                fit: BoxFit.cover,
                colorFilter:
                ColorFilter.mode(Colors.transparent, BlendMode.colorBurn)),
          ),


        ),
        placeholder: (context, url) => CircularProgressIndicator(),
        fadeInDuration: new Duration(seconds: 3),
        fadeOutDuration: new Duration(seconds: 1),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getPicList();
  }

  _getPicList() async {
    String url = "https://api.apiopen.top/getImages?page=$page&count=20";
    var httpClient = new HttpClient();
    try {
      var req = await httpClient.getUrl(Uri.parse(url));
      var res = await req.close();
      if (res.statusCode == HttpStatus.ok) {
        var jsonString = await res.transform(utf8.decoder).join(); //将结果转换成字符串拼接
        Map data = jsonDecode(jsonString); //格式化成map对象
        List pics = data['result'];
        List<PicModel> items = new List();
        for (var value in pics) {
          items.add(new PicModel.fromJson(value));
        }
        setState(() {
          this.picList.addAll(items);
          this.page++;
        });
      }
    } catch (e) {}
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
